﻿using IdentityData.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace PermissionApi.Controllers
{
    /// <summary>
    /// 账户
    /// </summary>
    [Route("api/account")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        private readonly AccountService _accountService;
        private readonly SigninService _signinService;
        public AccountController(AccountService accountService,SigninService signinService)
        {
            _accountService = accountService;
            _signinService = signinService;
        }

        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<ApplicationUser>>> GetAsync()
        {
            var users = await _accountService.FindEntitiesAsync(x => true);
            return users;
        }


        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="user"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<IdentityResult>> PostAsync([FromBody] ApplicationUser user,string password)
        {
            var res = await _accountService.CreateAsync(user, password);
            return res;
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="id"></param>
        /// <param name="value"></param>
        [HttpPut]
        public async Task<ActionResult<IdentityResult>> PutAsync([FromBody] ApplicationUser user)
            => await _accountService.UpdateAsync(user);

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id">用户Id</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult<IdentityResult>> DeleteAsync(string id)
        {
            var user =await _accountService.FindByIdAsync(id);
            if (user==null)
            {
                var res = new IdentityResult();
                return NotFound("用户不存在");
            }
            var returnRes =await _accountService.DeleteAsync(user);
            return returnRes;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user"></param>
        /// <param name="password"></param>
        /// <param name="lockoutOnFailure"></param>
        /// <returns></returns>
        [HttpPost("signin")]
        public async Task<ActionResult> SigninAsync(ApplicationUser user,string password,bool lockoutOnFailure)
        {
            await _signinService.SigninAsync(user, password, lockoutOnFailure);
            return Ok("Successed");
        }
    }
}
